package com.zbkj.crmeb.order.channel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.plat.by.dto.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.crmeb.core.common.CommonResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.crmeb.core.config.RestTemplateConfig;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.request.OrangeOrderRequest;
import com.zbkj.crmeb.order.request.OrangeOrderRequest.OrangeItem;
import com.zbkj.crmeb.order.response.OrangeOrderResponse;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class OrangeStoreOrderServiceImpl extends AbstractStoreOrderService {
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    IChannelMerchantService channelMerchantService;
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    StoreOrderFactory storeOrderFactory;

    /********* orange配置参数  *********/
    @Value("${orangeProduct.url}")
    private String orangeUrl;
    @Value("${orangeProduct.appId}")
    private String orangeAppId;
    @Value("${orangeProduct.secret}")
    private String orangeSecret;

    @Override
    public CommonResult<Object> addChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        try {
            // 组建订单对象
            OrangeOrderRequest orangeOrderRequest = new OrangeOrderRequest();
            List<OrangeItem> items = new ArrayList<>();
            BigDecimal price = BigDecimal.ZERO;
            Integer tempId = null;
            for (StoreOrderInfoVo order : orderInfoVoList) {
                tempId = order.getInfo().getProductInfo().getTempId();
                String barCode = order.getInfo().getProductInfo().getBarCode();
                String sourceItemId = barCode.substring(4, barCode.lastIndexOf("-"));
                String skuId = order.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
                if(skuId.startsWith(ProductTypeEnum.ORANGE.getCode()+"-")){
                    skuId = skuId.replaceFirst(ProductTypeEnum.ORANGE.getCode()+"-","");
                }
                String sourceSkuId = skuId.substring(0, skuId.lastIndexOf("-"));
                String channelType = skuId.substring(skuId.lastIndexOf("-")+1);
                //商品信息
                OrangeItem item = new OrangeItem();
                item.setChannelType(channelType)
                        .setItemId(sourceItemId)
                        .setSkuId(sourceSkuId)
                        .setBuyNum(order.getInfo().getCartNum());
                BigDecimal multiply = order.getInfo().getProductInfo().getAttrInfo().getSourceCost().multiply(new BigDecimal(order.getInfo().getCartNum()));
                price = price.add(multiply);
                items.add(item);
            }
            if(9 != storeOrder.getSource()) {
                storeOrder.setPushOrderNo(orderInfoVoList.get(0).getChildOrderNumber());
            }
            orangeOrderRequest.setSkuList(items)
                    .setAppId(orangeAppId)
                    //推送订单号
                    .setUserOrderNum(storeOrder.getPushOrderNo())
                    .setIdCardNumber(storeOrder.getIdCard())
                    .setPrice(price.doubleValue());
            //设置地址
            setAddr(storeOrder,orangeOrderRequest,tempId);
            Result result = pushOrder(storeOrder, orangeOrderRequest, orderInfoVoList);
            if(!result.isSuccess()){
                return CommonResult.failed(result.getMessage());
            }
        } catch (Exception e) {
            log.info("--------------- 请求ORANGE创建订单失败: {} ---------------", e.getMessage());
        }
        return CommonResult.success();
    }

    private Result pushOrder(StoreOrder storeOrder, OrangeOrderRequest req, List<StoreOrderInfoVo> orderInfoVoList) throws JsonProcessingException {
        String orderId = storeOrder.getSource() == 9 ? storeOrder.getOrderId().split("-")[0] : storeOrder.getOrderId();
        StringBuilder sb = new StringBuilder().append(orangeUrl)
                .append("order/create_order.do");
        String param = JSONObject.toJSONString(req);
        String sign = DigestUtils.md5Hex(param+orangeSecret).toUpperCase();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("SIGN", sign);
        log.info("--------------- 开始请求ORANGE创建订单url: {} ,参数:{}---------------", sb.toString(),param);
        HttpEntity<String> requestEntity = new HttpEntity<>(param, headers);
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        ResponseEntity<String> response = restTemplate.postForEntity(sb.toString(), requestEntity, String.class);
        if (HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");
            log.info("--------------- {} ---------------", errorMessage);
        }
        log.info("--------------- 请求ORANGE创建订单返回结果: {} ---------------", response.toString());
        ObjectMapper mapper = new ObjectMapper();
        OrangeOrderResponse orangeOrderResponse = mapper.readValue(response.getBody(), OrangeOrderResponse.class);
        String channelOrdersn = null;
        if(Objects.equals(orangeOrderResponse.getSuccess(),1)){
            channelOrdersn= orangeOrderResponse.getData().getOrderNum();
            //新增采购单
            storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.ORANGE.getCode());
            //新增采购商品
            storeOrderFactory.insertPurchaseGoods(orderInfoVoList, storeOrder, true, orangeOrderResponse.getMessage(), channelOrdersn, false);

            StoreOrder storeOrderUpdate = new StoreOrder();
            storeOrderUpdate.setId(storeOrder.getId());
            storeOrderUpdate.setPushStatus(1);
            storeOrderUpdate.setPushMessage("ORANGE推送:" + orangeOrderResponse.getMessage());
            storeOrderDao.updateById(storeOrderUpdate);
            log.info("--------------- ORANGE下订单成功:{} ---------------", orangeOrderResponse.getMessage());
            return new Result(true, null, orangeOrderResponse.getMessage());
        }
        // 新增采购单
        storeOrderFactory.insertPurchaseOrder(storeOrder, false, PurchaseOrderChannelTypeEnum.ORANGE.getCode());
        // 新增采购商品
        storeOrderFactory.insertPurchaseGoods(orderInfoVoList, storeOrder, false, orangeOrderResponse.getMessage(), null, false);
        StoreOrder storeOrderUpdate = new StoreOrder();
        storeOrderUpdate.setId(storeOrder.getId());
        storeOrderUpdate.setPushStatus(2);
        storeOrderUpdate.setPushMessage("ORANGE推送:" + orangeOrderResponse.getMessage());
        storeOrderDao.updateById(storeOrderUpdate);
        log.info("--------------- 下订单失败:{} ---------------", orangeOrderResponse.getMessage());
        return new Result(false, null, orangeOrderResponse.getMessage());
    }

    private void setAddr(StoreOrder storeOrder,OrangeOrderRequest request,Integer tempId){
        request.setName(storeOrder.getRealName());
        String phone = storeOrder.getUserPhone();
        if(phone.contains(" ")){
            phone = phone.substring(phone.indexOf(" ")+1);
        }
        request.setPhone(phone);
        request.setProvince(storeOrder.getProvince());
        request.setCity(storeOrder.getCity());
        request.setDistrict(storeOrder.getDistrict());
        request.setAddress(storeOrder.getDetail());
        //发货地大陆
//        if(StockAreaTempEnum.getByTempId(tempId).equals(StockAreaTempEnum.CN)){
//            request.setName(storeOrder.getRealName());
//            request.setPhone(storeOrder.getUserPhone());
//            request.setProvince(storeOrder.getProvince());
//            request.setCity(storeOrder.getCity());
//            request.setDistrict(storeOrder.getDistrict());
//            request.setAddress(storeOrder.getDetail());
//        }else {
//            ChannelMerchant merchant = channelMerchantService.getById(storeOrder.getMerId());
//            if(!Objects.isNull(merchant)){
//                String detail = merchant.getDetail();
//                String[] addr = net.logstash.logback.encoder.org.apache.commons.lang.StringUtils.isNotBlank(detail) ? detail.split("\\s+") : new String[1];
//                if(5 == addr.length ){
//                    request.setProvince(addr[1]);
//                    request.setCity(addr[2]);
//                    request.setDistrict(addr[3]);
//                    request.setAddress(addr[4]);
//                }
//                request.setName(merchant.getConsigneeName());
//                request.setPhone(merchant.getConsigneePhone());
//            }
//        }
    }

    @Override
    public CommonResult<Object> cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        return null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        return null;
    }
}
